;;;; Load this file and start a test server at http://localhost:4242

(ql:quickload :easy-routes)
(ql:quickload :cl-fad)
(ql:quickload :cl-daisyui)


(defparameter *http-port* 4242)
(defparameter *www-dir*
  (cl-fad:merge-pathnames-as-directory (asdf:system-source-directory :cl-daisyui) #P"www/"))
(defvar *acceptor* nil)

;; component files
(load (cl-fad:merge-pathnames-as-file *www-dir* "icons.lisp"))
(load (cl-fad:merge-pathnames-as-file *www-dir* "actions.lisp"))
(load (cl-fad:merge-pathnames-as-file *www-dir* "data-display.lisp"))
(load (cl-fad:merge-pathnames-as-file *www-dir* "navigation.lisp"))
(load (cl-fad:merge-pathnames-as-file *www-dir* "feedback.lisp"))
(load (cl-fad:merge-pathnames-as-file *www-dir* "data-input.lisp"))
(load (cl-fad:merge-pathnames-as-file *www-dir* "layout.lisp"))
;; page files
(load (cl-fad:merge-pathnames-as-file *www-dir* "index.lisp"))
(load (cl-fad:merge-pathnames-as-file *www-dir* "content.lisp"))
(load (cl-fad:merge-pathnames-as-file *www-dir* "components.lisp"))


(defun proxy-redirect (target
                       &rest args
                       &key (protocol (if (string= (hunchentoot:header-in* :x-forwarded-proto) "https") :https :http))
                       &allow-other-keys)
  "hunchentoot:redirect version after utilizing the nginx proxy.
https://stackoverflow.com/questions/72062476/how-to-redirect-to-https-when-hunchentoot-is-behind-a-reverse-proxy
"
  (apply #'hunchentoot:redirect target :protocol protocol args))


(defun start-webserver (&key (address "0.0.0.0") (port *http-port*) (root *www-dir*))
  ;; easy-routes:routes-acceptor cannot serve static files by default, easy-routes:easy-routes-acceptor can serve static files
  (setf *acceptor* (make-instance 'easy-routes:easy-routes-acceptor
                                  :port port :address address
                                  :document-root root
                                  ))
  (log:info "Webserver started on \"~d:~d\"~%." address port)
  (hunchentoot:start *acceptor*))


(defun stop-webserver ()
  (hunchentoot:stop *acceptor*)
  (log:info "Webserver has been shutted down.~%")
  (setf *acceptor* nil))


(start-webserver)
